package com.persondemo.videoappliction.ui.dianping;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.DianPingDetilsBean;
import com.persondemo.videoappliction.bean.ShopDetilsBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.ui.adapter.DPdetilsAdapter;
import com.persondemo.videoappliction.ui.base.AppManager;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.dianping.contract.DPdetilsContract;
import com.persondemo.videoappliction.ui.dianping.presenter.DPdetilsPresenter;
import com.persondemo.videoappliction.ui.image.ImageDetailsActivity;
import com.persondemo.videoappliction.utils.ActionSheetDialog;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.widget.CustomLoadMoreView;
import com.persondemo.videoappliction.widget.SimpleMultiStateView;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class DianPingDetilsActivity extends BaseActivity<DPdetilsPresenter> implements DPdetilsContract.View, View.OnClickListener {
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.SimpleMultiStateView)
    com.persondemo.videoappliction.widget.SimpleMultiStateView SimpleMultiStateView;
    @BindView(R.id.mPtrFrameLayout)
    PtrClassicFrameLayout mPtrFrameLayout;
    @BindView(R.id.dianping_write)
    LinearLayout dianpingWrite;
    @BindView(R.id.dianping_phone)
    LinearLayout dianpingPhone;
    @BindView(R.id.tou_relate)
    RelativeLayout touRelate;
    @BindView(R.id.dianping_back)
    ImageView dianpingBack;
    @BindView(R.id.shop_title)
    TextView shopTitle;
    @BindView(R.id.dianping_liner)
    LinearLayout dianpingLiner;
    private View headview;
    private ImageView dingping_banner;
    private RatingBar detils_Ratingbar;
    private LinearLayout loaciton_liner;
    private TextView detils_loaction;
    private TextView detils_time;
    private TextView detils_pingjia_num, foot_text, dpshop_title;
    private Button detils_btn01, detils_btn02, detils_btn03, detils_btn04;
    private DPdetilsAdapter adapter;
    private List<DianPingDetilsBean.DataBean.ListBean> list = null;
    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;
    int mheight;
    int all;
    private String id;
    private String phone = "", type = "";
    private String xlocation, ylocation, adress;
    private int page = 1;
    private View footview;
    private int haoping = 0, youtu = 0, chaping = 0;
    private ArrayList<String> arrayList;

    @Override
    public void onRetry() {

    }

    @Override
    public int getContentLayout() {
        return R.layout.module_activity_dianpingdeitls;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void bindView(View view, Bundle savedInstanceState) {
        headview = getLayoutInflater().inflate(R.layout.module_head_dpdetils, null);
        footview = getLayoutInflater().inflate(R.layout.dianpingdetils_foot, null);
        foot_text = footview.findViewById(R.id.foot_text);
        dpshop_title = headview.findViewById(R.id.dpshop_title);
        dingping_banner = headview.findViewById(R.id.dingping_banner);
        detils_Ratingbar = headview.findViewById(R.id.detils_Ratingbar);
        loaciton_liner = headview.findViewById(R.id.loaciton_liner);
        detils_loaction = headview.findViewById(R.id.detils_loaction);
        detils_time = headview.findViewById(R.id.detils_time);
        detils_pingjia_num = headview.findViewById(R.id.detils_pingjia_num);
        detils_btn01 = headview.findViewById(R.id.detils_btn01);
        detils_btn02 = headview.findViewById(R.id.detils_btn02);
        detils_btn03 = headview.findViewById(R.id.detils_btn03);
        detils_btn04 = headview.findViewById(R.id.detils_btn04);
        loaciton_liner.setOnClickListener(this);
        detils_btn01.setOnClickListener(this);
        detils_btn02.setOnClickListener(this);
        detils_btn03.setOnClickListener(this);
        detils_btn04.setOnClickListener(this);
        dianpingWrite.setOnClickListener(this);
        dianpingPhone.setOnClickListener(this);
        touRelate.setOnClickListener(this);
        foot_text.setOnClickListener(this);
        dingping_banner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (arrayList.size() > 0) {
                    Intent i = new Intent(DianPingDetilsActivity.this, ImageDetailsActivity.class);
                    i.putStringArrayListExtra("list_img", arrayList);
                    startActivity(i);
                }
            }
        });
        mPtrFrameLayout.disableWhenHorizontalMove(true);
        touRelate.setBackgroundColor(Color.argb(0, 255, 114, 10));
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mRecyclerView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {

            }
        });

        ViewTreeObserver vto = dingping_banner.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                mheight = dingping_banner.getMeasuredHeight();
                return true;
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int scrollY) {
                all += scrollY;
                if (all <= 0) {
                    dianpingBack.setVisibility(View.VISIBLE);
                    touRelate.setVisibility(View.GONE);
                    touRelate.setBackgroundColor(Color.argb(0, 255, 132, 0));
                } else if (all > 0 && all <= mheight) {
                    dianpingBack.setVisibility(View.GONE);
                    dianpingLiner.setVisibility(View.GONE);
                    touRelate.setVisibility(View.VISIBLE);
                    float scale = (float) all / mheight;
                    float alpha = (255 * scale);
                    Log.i("lidaming", "alpha=" + alpha + "mheihht=" + mheight + "scrollY=" + all);
                    touRelate.setBackgroundColor(Color.argb((int) alpha, 255, 132, 0));
                } else {
                    dianpingBack.setVisibility(View.GONE);
                    touRelate.setVisibility(View.VISIBLE);
                    touRelate.setBackgroundColor(Color.argb(255, 255, 132, 0));
                }
            }
        });
        mRecyclerView.setLayoutManager(new GridLayoutManager(DianPingDetilsActivity.this, 1));
        adapter = new DPdetilsAdapter(list, DianPingDetilsActivity.this);
        mRecyclerView.setAdapter(adapter);
        adapter.setEnableLoadMore(false);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });

    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        Log.i("id", "id=" + id);
        list = new ArrayList<>();
        arrayList = new ArrayList<>();
        if (mPresenter != null) {
            showLoadingDialog();
            mPresenter.getshop(id);
            mPresenter.getdainping(id, page + "", type);
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loaciton_liner:
                gotoditu();
                break;
            case R.id.detils_btn01:
                page = 1;
                type = "";
                if (mPresenter != null) {
                    showLoadingDialog();
                    list.clear();
                    adapter.notifyDataSetChanged();
                    mPresenter.getdainping(id, page + "", type);
                }
                break;
            case R.id.detils_btn02:
                type = "3";
                page = 1;
                if (youtu == 0) {
                    T.showShort(DianPingDetilsActivity.this, "暂时没有评价!");
                    return;
                }
                if (mPresenter != null) {
                    showLoadingDialog();
                    list.clear();
                    adapter.notifyDataSetChanged();
                    mPresenter.getdainping(id, page + "", type);
                }
                break;
            case R.id.detils_btn03:
                type = "1";
                page = 1;
                if (haoping == 0) {
                    T.showShort(DianPingDetilsActivity.this, "暂时没有评价!");
                    return;
                }
                if (mPresenter != null) {
                    showLoadingDialog();
                    list.clear();
                    adapter.notifyDataSetChanged();
                    mPresenter.getdainping(id, page + "", type);
                }
                break;
            case R.id.detils_btn04:
                type = "2";
                page = 1;
                if (chaping == 0) {
                    T.showShort(DianPingDetilsActivity.this, "暂时没有评价!");
                    return;
                }
                if (mPresenter != null) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                    showLoadingDialog();
                    mPresenter.getdainping(id, page + "", type);
                }
                break;
            case R.id.dianping_write:
                Intent intent = new Intent(DianPingDetilsActivity.this, PutDianPingActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.dianping_phone:
                call(phone);
                break;
            case R.id.tou_relate:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.foot_text:
                if (!TextUtils.isEmpty(id)) {
                    gopinlun(id);
                }
                break;
        }

    }

    private void gopinlun(String id) {
        Intent intent = new Intent(DianPingDetilsActivity.this, PinglunActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void gotoditu() {
        new ActionSheetDialog(DianPingDetilsActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("百度地图", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {

                                openBaiduMap();
                            }
                        })
                .addSheetItem("高德地图", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {

                                openGaodeMap();
                            }
                        }).show();
    }

    //调用高德地图
    private void openGaodeMap() {
        if (isInstallByread("com.autonavi.minimap")) {
            Intent intent = new Intent("android.intent.action.VIEW", Uri.parse("androidamap://viewMap?sourceApplication=爱车点点&poiname=+" + adress + "&lat=" + ylocation + "&lon=" + xlocation + "&dev=0"));
            intent.setPackage("com.autonavi.minimap");
            startActivity(intent);
        } else {
            Toast.makeText(getApplicationContext(), "未安装高德地图客户端", Toast.LENGTH_SHORT).show();
        }
    }

    //调用百度地图
    private void openBaiduMap() {
        Intent intent = null;
        if (isInstallByread("com.baidu.BaiduMap")) {
            try {
                intent = Intent.getIntent("intent://map/marker?location=" + ylocation + "," + xlocation + "&title=" + adress + "&content=" + adapter + "&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                startActivity(intent);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

        } else {
            Toast.makeText(getApplicationContext(), "未安装百度地图客户端", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    private void call(String tell) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(DianPingDetilsActivity.this, Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(DianPingDetilsActivity.this, new String[]
                        {Manifest.permission.CALL_PHONE}, REQUEST_CODE_ASK_CALL_PHONE);
                return;
            } else {
                //上面已经写好的拨号方法
                callDirectly(tell);
            }
        } else {
            //上面已经写好的拨号方法
            callDirectly(tell);
        }
    }

    private void callDirectly(String mobile) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.CALL");
        intent.setData(Uri.parse("tel:" + mobile));
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void loadshop(ShopDetilsBean shopDetilsBean) {
        hideLoadingDialog();
        if (shopDetilsBean.getStatus() == 1) {
            shopTitle.setText(shopDetilsBean.getData().getTitle());
            ImageLoaderUtil.LoadImage(DianPingDetilsActivity.this, shopDetilsBean.getData().getImgs(), dingping_banner);
            arrayList.add(shopDetilsBean.getData().getImgs());
            detils_Ratingbar.setRating(Float.parseFloat(shopDetilsBean.getData().getPing()));
            detils_loaction.setText(shopDetilsBean.getData().getAddress());
            detils_time.setText("营业时间：" + shopDetilsBean.getData().getBusiness());
            dpshop_title.setText(shopDetilsBean.getData().getTitle());
            phone = shopDetilsBean.getData().getPhone();
            adress = shopDetilsBean.getData().getAddress();
            xlocation = shopDetilsBean.getData().getXlocation();
            ylocation = shopDetilsBean.getData().getYlocation();
        } else {
            T.showShort(DianPingDetilsActivity.this, shopDetilsBean.getMsg());
        }
    }

    @Override
    public void loaddianping(DianPingDetilsBean dianPingDetilsBean) {
        hideLoadingDialog();
        if (dianPingDetilsBean.getStatus() == 1) {
            if (dianPingDetilsBean.getData().getTotal() != 0) {
                detils_btn01.setText("最新评价(" + dianPingDetilsBean.getData().getTotal() + "）");
            }
            youtu = dianPingDetilsBean.getData().getYpnum();
            if (dianPingDetilsBean.getData().getYpnum() != 0) {
                detils_btn02.setText("有图(" + dianPingDetilsBean.getData().getYpnum() + ")");
            }
            haoping = dianPingDetilsBean.getData().getHpnum();
            if (dianPingDetilsBean.getData().getHpnum() != 0) {
                detils_btn03.setText("好评(" + dianPingDetilsBean.getData().getHpnum() + ")");
            }
            chaping = dianPingDetilsBean.getData().getCpnum();
            if (dianPingDetilsBean.getData().getCpnum() != 0) {
                detils_btn04.setText("(差评(" + dianPingDetilsBean.getData().getCpnum() + ")");
            }

            if (dianPingDetilsBean.getData().getList() == null || dianPingDetilsBean.getData().getList().size() == 0) {
                hideLoadingDialog();
                T.showShort(DianPingDetilsActivity.this, "没有更多数据了！");
                list.clear();
                adapter.setNewData(null);
                adapter.removeAllHeaderView();
                adapter.addHeaderView(headview);
                return;
            }
            if (dianPingDetilsBean.getData().getList() != null && dianPingDetilsBean.getData().getList().size() > 0) {
                list.clear();
                adapter.removeAllHeaderView();
                adapter.removeAllFooterView();
                list = dianPingDetilsBean.getData().getList();
                adapter.setNewData(list);
                mPtrFrameLayout.refreshComplete();
                showSuccess();
                adapter.addFooterView(footview);
                adapter.addHeaderView(headview);
            }
        } else {
            T.showShort(DianPingDetilsActivity.this, dianPingDetilsBean.getMsg());
        }
    }

    @Override
    public void loadmore(DianPingDetilsBean dianPingDetilsBean) {

    }

    @OnClick(R.id.dianping_liner)
    public void onViewClicked() {
        AppManager.getAppManager().finishActivity();
    }
}
